package com.wanpinghui.supplier.product;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.addrbook.CustomerInfoActivity;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.message.MessageP2PActivity;
import com.wanpinghui.supplier.product.adapter.CartListAdapter;
import com.wanpinghui.supplier.utils.ActivityJumpUtil;
import com.wanpinghui.supplier.widgets.TitlePanelLayoutUser;
import com.wanpinghui.wphlibrary.WPHSdk;
import com.wanpinghui.wphlibrary.model.oauth.OAuthService;
import com.wanpinghui.wphlibrary.model.oauth.bean.UserBean;
import com.wanpinghui.wphlibrary.model.order.bean.SingleOrderItem;
import com.wanpinghui.wphlibrary.model.product.ProductService;
import com.wanpinghui.wphlibrary.model.product.bean.CartBean;
import com.wanpinghui.wphlibrary.model.product.bean.EditCartItemCountParams;
import com.wanpinghui.wphlibrary.model.product.bean.OrderCreateParams;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.lang.ref.WeakReference;
import java.util.List;

import retrofit.callback.YRequestCallback;

/***
 * 功能描述:购物车列表
 * 作者:qiujialiu
 * 时间:2017/12/21
 ***/
@ContentView(R.layout.layout_activity_cart_list)
public class CartListActivity extends BaseActivity {
    @ViewInject(R.id.recv_cart)
    private RecyclerView recyclerViewCart;
    @ViewInject(R.id.tpl_title)
    private TitlePanelLayoutUser mLayoutTitle;
    @ViewInject(R.id.textView4)
    private TextView textViewReload;
    //    @ViewInject(R.id.ll_bottom)
//    private LinearLayout layoutBottom;
    @ViewInject(R.id.rl_no_data)
    private RelativeLayout relativeLayoutNoData;
    @ViewInject(R.id.tv_go_product)
    private TextView textViewGoProduct;

    private CartListAdapter mAdapter;
    private CLAHandler mHandler;
    private EditCartItemCountParams params;
    private int userId;
    private int supplierId;

    @Override
    public String getName() {
        return null;
    }

    @Override
    public boolean isBar() {
        return false;
    }

    @Override
    public void initViews() {
        mAdapter = new CartListAdapter(this);
        recyclerViewCart.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewCart.setAdapter(mAdapter);
        mHandler = new CLAHandler(this);
        if (getIntent() != null) {
            userId = getIntent().getIntExtra("buyer", 0);
            supplierId = getIntent().getIntExtra("supplier", 0);
        }
    }

    @Override
    public void bindEvents() {
        mAdapter.setSelectChangeListener(new CartListAdapter.SelectChangeListener() {
            @Override
            public void onBuy(OrderCreateParams params) {
                createOrder(params);
            }

            @Override
            public void onItemCountChange(int id, int count) {
                params = new EditCartItemCountParams(id, count);
                mHandler.removeMessages(1);
                mHandler.sendEmptyMessageDelayed(1, 400);
            }
        });
        mLayoutTitle.setOnClickBacktrack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        textViewReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textViewReload.setVisibility(View.GONE);
                initData();
            }
        });

        textViewGoProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (userId != 0 && supplierId != 0) {
                    Intent intent = new Intent(CartListActivity.this, ProductListActivity.class);
                    intent.putExtra("buyer", userId);
                    intent.putExtra("supplier",supplierId);
                    startActivity(intent);
                }else {
                    ActivityJumpUtil.startProductList(CartListActivity.this);
                }
            }
        });
    }

    @Override
    public void initData() {
        WPHSdk.getService(ProductService.class)
                .getCartList(new YRequestCallback<List<CartBean>>() {
                    @Override
                    public void onSuccess(List<CartBean> var1) {
                        textViewReload.setVisibility(View.GONE);
                        if (var1 == null || var1.size() == 0) {
                            relativeLayoutNoData.setVisibility(View.VISIBLE);
                        } else {
                            relativeLayoutNoData.setVisibility(View.GONE);
                        }
                        mAdapter.setData(var1);
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        textViewReload.setVisibility(View.VISIBLE);
                        textViewReload.setText(message + "，点击重新加载");
                    }

                    @Override
                    public void onException(Throwable var1) {
                        textViewReload.setVisibility(View.VISIBLE);
                        textViewReload.setText("加载出错，点击重新加载");
                    }
                });
//        CartDbManager.getInstance().getCartProduct(new YRequestCallback<List<ProductBean>>() {
//            @Override
//            public void onSuccess(List<ProductBean> var1) {
//                CartBean cartBean = new CartBean();
//                cartBean.setProducts(var1);
//                mAdapter.setData(cartBean);
//            }
//
//            @Override
//            public void onFailed(int var1, String message) {
//
//            }
//
//            @Override
//            public void onException(Throwable var1) {
//                var1.printStackTrace();
//            }
//        });
    }

    private void changeCount() {
        if (params != null) {
            WPHSdk.getService(ProductService.class)
                    .changeCartItemCount(params, new YRequestCallback() {
                        @Override
                        public void onSuccess(Object var1) {

                        }

                        @Override
                        public void onFailed(int var1, String message) {
                            showWarningText(message);
                        }

                        @Override
                        public void onException(Throwable var1) {
                            var1.printStackTrace();
                        }
                    });
        }
    }

    private void createOrder(final OrderCreateParams orderCreateParams) {
        if (orderCreateParams == null) return;
        WPHSdk.getService(ProductService.class)
                .createOrder(orderCreateParams, new YRequestCallback<SingleOrderItem>() {
                    @Override
                    public void onSuccess(SingleOrderItem var1) {
                        UserBean userBean = WPHSdk.getService(OAuthService.class).getUserInfo(null);
                        if (orderCreateParams.getBuyer_id() == Integer.parseInt(userBean.getUser().getId())) {
                            MessageP2PActivity.start(CartListActivity.this, orderCreateParams.getSeller_id(), new Gson().toJson(var1));
                        } else {
                            MessageP2PActivity.start(CartListActivity.this, orderCreateParams.getBuyer_id(), new Gson().toJson(var1));
                        }
                        initData();
                    }

                    @Override
                    public void onFailed(int var1, String message) {
                        showWarningText(message);
                    }

                    @Override
                    public void onException(Throwable var1) {
                        var1.printStackTrace();
                        showWarningText("出错了[" + var1.toString() + "]");
                    }
                });
    }

    static class CLAHandler extends Handler {
        private WeakReference<CartListActivity> mActivity;

        public CLAHandler(CartListActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    CartListActivity activity = mActivity.get();
                    if (activity != null) {
                        activity.changeCount();
                    }
                    break;
            }
        }
    }
}
